<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" :default-params="{ adCode: [] }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="案例风格" name="style">
          <t-select
            v-model:value="params.style"
            :options="dictionaryStore.get('case_style')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="房屋户型" name="houseType">
          <t-select
            v-model:value="params.houseType"
            :options="dictionaryStore.get('decoration_order_house_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <!-- <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col> -->
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="案例标题" name="title">
          <t-input v-model:value="params.title" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="caseListCRUD.page"
      column-controller-key="caseList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['system:case:create']"
            @click="
              handleOpenDialog('create', {
                adCode: [],
                coverImage: [],
                vrFileUrls: [],
                engineeringFileUrl: [],
                designerAvatarList: [],
                designerTags:[],
                designerStyle:[]
              })
            "
          >
            新建案例
          </t-button>
        </div>
      </template>
      <template #style="{ row }">
        {{ dictionaryStore.analysis('case_style', row.style) }}
      </template>
      <template #houseType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
      </template>
      <template #houseArea="{ row }">
        {{ dictionaryStore.analysis('area', row.houseArea) }}
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #propertyName="{ row }">
        {{ propertyInfoList.find((item) => item.id === row.propertyName)?.name }}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #designerId="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:case:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:case:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:case:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="caseListCRUD"
      header="*案例"
      width="75%"
      :on-before-set-data="handleDialogSetData"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-row :gutter="[20, 20]" style="width: 100%">
        <t-col :span="4">
          <t-form-item label="案例风格" name="style" :rules="[{ required: true, message: '请选择案例风格' }]">
            <t-select
              v-model:value="formData.style"
              :options="dictionaryStore.get('case_style')"
              placeholder="请选择案例风格"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.style = null"
            />
          </t-form-item>
          <t-form-item label="房屋户型" name="houseType" :rules="[{ required: true, message: '请选择房屋户型' }]">
            <t-select
              v-model:value="formData.houseType"
              :options="dictionaryStore.get('decoration_order_house_type')"
              placeholder="请选择房屋户型"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.houseType = null"
            />
          </t-form-item>
          <t-form-item label="房屋面积(㎡)" name="houseArea" :rules="[{ required: true, message: '请选择房屋面积' }]">
            <t-select
              v-model:value="formData.houseArea"
              :options="dictionaryStore.get('area')"
              placeholder="请选择房屋面积"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.houseArea = null"
            />
          </t-form-item>
          <!-- <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
            <t-cascader
              v-model:value="formData.adCode"
              :options="city.tree"
              :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
              placeholder="请选择归属城市"
              filterable
              clearable
              :readonly="readonly"
              value-type="full"
              @change="(value: any) => handleAdCodeChange(value, formData)"
            />
          </t-form-item> -->
          <t-form-item label="楼盘名称" name="propertyName" :rules="[{ required: true, message: '请选择楼盘名称' }]">
            <t-select
              v-model:value="formData.propertyName"
              v-model:popup-visible="formData.popupVisible"
              placeholder="请选择楼盘名称"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.propertyName = null"
            >
              <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
                {{ _.name }}
                <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
              </t-option>
              <template #panelBottomContent>
                <!-- 快捷添加楼盘信息 -->
                <quick-add-property-info
                  @open="formData.popupVisible = false"
                  @close="((formData.popupVisible = true), handleGetPropertyInfoList())"
                />
              </template>
            </t-select>
          </t-form-item>
          <t-form-item label="案例标题" name="title" :rules="[{ required: true, message: '请输入案例标题' }]">
            <t-input v-model:value="formData.title" placeholder="请输入案例标题" clearable :readonly="readonly" />
          </t-form-item>
          <t-form-item label="案例图片" name="coverImage" :rules="[{ required: true, message: '请上传案例图片' }]">
            <upload v-model:files="formData.coverImage" accept="image/*" theme="image" :disabled="readonly" />
          </t-form-item>
          <t-form-item
            label="施工图片"
            name="engineeringFileUrl"
            :rules="[{ required: true, message: '请上传施工图片' }]"
          >
            <upload
              v-model:files="formData.engineeringFileUrl"
              accept="image/*"
              multiple
              theme="image"
              :disabled="readonly"
            />
          </t-form-item>
          <t-form-item
            label="设计师"
            name="designerName"
            :rules="[{ required: true, message: '请选择设计师' }]"
          >
            <t-select
              v-model:value="formData.designerName"
              :options="userStore.simpleUserList"
              :keys="{ label: 'nickname', value: 'nickname' }"
              placeholder="请选择设计师"
              clearable
              filterable
              :readonly="readonly"
              @change="(value) => handleSetDesignerInfo(value, formData)"
              @clear="formData.designerName = null"
            />
          </t-form-item>
          <template v-if="formData.designerName">
            <t-form-item
              label="设计师手机号"
              name="designerPhone"
              :rules="[{ required: true, message: '请选择设计师手机号' }]"
            >
              <t-input v-model:value="formData.designerPhone" placeholder="请选择设计师手机号" clearable readonly />
            </t-form-item>
            <t-form-item
              label="设计师微信号"
              name="designerWxCode"
              :rules="[{ required: true, message: '请输入设计师微信号' }]"
            >
              <t-input
                v-model:value="formData.designerWxCode"
                placeholder="请输入设计师微信号"
                clearable
                :readonly="readonly"
              />
            </t-form-item>
            <t-form-item
              label="设计师头像"
              name="designerAvatar"
              :rules="[{ required: true, message: '请上传设计师头像' }]"
            >
              <upload
                v-model:files="formData.designerAvatarList"
                accept="image/*"
                theme="image"
                :disabled="readonly"
                @change="
                  (value) => {
                    formData.designerAvatar = value[0]?.url;
                  }
                "
              />
            </t-form-item>
            <t-form-item
              label="设计师能力"
              name="designerTags"
              :rules="[{ required: true, message: '请输入设计师个人能力' }]"
            >
            <t-space class="tag-block">
              <t-tag
                v-for="(tag, index) in formData.designerTags"
                :key="index"
                theme="primary"
                :closable="true"
                :disabled="readonly"
                @click="handleClick"
                @close="handleClose(index, formData.designerTags)"
              >
                {{ tag }}
              </t-tag>
            </t-space>
            <t-space class="tag-block editable" v-if="!readonly">
              <t-tag v-if="!inputVisible" @click="handleClickAdd">
                <add-icon />
                添加标签
              </t-tag>
              <t-input v-else ref="input" size="small" style="width: 94px" @blur="(value)=>handleInputEnter(value,formData.designerTags)" @enter="(value)=>handleInputEnter(value,formData.designerTags)" />
            </t-space>
            </t-form-item>
            <t-form-item
              label="设计师风格"
              name="designerStyle"
              :rules="[{ required: true, message: '请输入擅长风格' }]"
            >
            <t-space class="tag-block">
              <t-tag
                v-for="(tag, index) in formData.designerStyle"
                :key="index"
                theme="primary"
                :closable="true"
                :disabled="readonly"
                @click="handleClick"
                @close="handleClose(index, formData.designerStyle)"
              >
                {{ tag }}
              </t-tag>
            </t-space>
            <t-space class="tag-block editable" v-if="!readonly">
              <t-tag v-if="!inputVisibleStyle" @click="handleClickAddStyle">
                <add-icon />
                添加标签
              </t-tag>
              <t-input v-else ref="inputStyle" size="small" style="width: 94px" @blur="(value)=>handleInputEnterStyle(value,formData.designerStyle)" @enter="(value)=>handleInputEnterStyle(value,formData.designerStyle)" />
            </t-space>
            </t-form-item>
          </template>
        </t-col>
        <t-col :span="4">
          <t-form-item label="案例VR" name="vrFileUrls"  label-align="top">
            <div style="width: 100%">
              <t-table
                row-key="id"
                :data="formData.vrFileUrls"
                :columns="[
                  { colKey: 'space', title: '空间',align: 'center', width: 100 },
                  { colKey: 'fileUrlList',align: 'center', title: 'vr文件'},
                  { colKey: 'operation', align: 'center',title: '操作', width: 70, fixed: 'right' },
                ]"
                bordered
                size="small"
                stripe
                hover
              >
                <template #space="{ row, rowIndex }">
                  <t-form-item
                    label="空间"
                    :name="`vrFileUrls[${rowIndex}].space`"
                    :rules="[
                      { required: true, message: '请输入空间' },
                    ]"
                    label-width="0"
                  >
                    <t-input
                      v-model:value="row.space"
                      placeholder="请输入空间"
                      :readonly="readonly"
                      style="width: 100%"
                    />
                  </t-form-item>
                </template>
                <template #fileUrlList="{ row, rowIndex }">
                  <t-form-item
                    label="vr文件"
                    :name="`vrFileUrls[${rowIndex}].fileUrlList`"
                    :rules="[{ required: true, message: '请选择vr文件' }]"
                    label-width="0"
                  >
                   <upload v-model:files="row.fileUrlList" :disabled="readonly"  theme="image"  accept="image/*" />
                  </t-form-item>
                </template>
              
                <template #operation="{ rowIndex }">
                  <t-popconfirm
                    v-if="!readonly"
                    content="确认要删除该项吗？"
                    @confirm="formData.vrFileUrls.splice(rowIndex, 1)"
                  >
                    <t-link theme="danger"> 删除 </t-link>
                  </t-popconfirm>
                </template>
              </t-table>
              <t-button v-if="!readonly" block @click="formData.vrFileUrls.push({space:'',fileUrlList:[]})"> 添加案例VR </t-button>
            </div>
          </t-form-item>
        </t-col>
        <t-col :span="4">
          <t-form-item
            label="案例描述"
            name="remark"
            :rules="[{ required: true, message: '请输入案例描述' }]"
            label-align="top"
          >
            <wangeditor v-model:value="formData.remark" :readonly="readonly" />
          </t-form-item>
        </t-col>
      </t-row>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'CaseList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, SelectValue, TableCol } from 'tdesign-vue-next';
import { AddIcon } from 'tdesign-icons-vue-next';
import { nextTick, onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD } from '@/api/config/property';
import { caseListCRUD } from '@/api/distribution/case';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import Upload from '@/components/upload/index.vue';
import wangeditor from '@/components/wangeditor/index.vue';
import QuickAddPropertyInfo from '@/pages/config/property/components/QuickAddPropertyInfo.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import city from '@/utils/city';
import dataEncryption from '@/utils/dataEncryption';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '案例ID' },
  { colKey: 'style', title: '案例风格', width: 100 },
  { colKey: 'houseType', title: '房屋户型', width: 100 },
  { colKey: 'houseArea', title: '房屋面积', width: 120 },
  // { colKey: 'adCode', title: '归属城市', width: 250 },
  { colKey: 'propertyName', title: '楼盘名称', width: 200 },
  { colKey: 'title', title: '案例标题', width: 200 },
  { colKey: 'designerName', title: '设计师', width: 100 },
  { colKey: 'seeCount', title: '查看数量', width: 100 },
  { colKey: 'forwardCount	', title: '转发数量', width: 100 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  if (!params.adCode.length) {
    delete params.province;
    delete params.city;
    delete params.area;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetPropertyInfoList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  // 归属城市
  params.adCode = [];
  if (params.province) params.adCode.push(params.province);
  if (params.city) params.adCode.push(params.city);
  if (params.area) params.adCode.push(params.area);
  // 设计师头像
  params.designerAvatarList = [];
  if (params.designerAvatar) params.designerAvatarList.push({ url: params.designerAvatar });
  if (params.vrFileUrls&&params.vrFileUrls.length>0) {
    const groupedData = params.vrFileUrls.reduce((acc:any, item:any) => {
      if (!acc[item.space]) {
        acc[item.space] = [];
      }
      acc[item.space].push({ url: item.fileUrl });
      return acc;
    }, {});
    // 转换为目标结构
    params.vrFileUrls = Object.keys(groupedData).map(space => ({
        space,
        fileUrlList: groupedData[space]
    }));
    console.log(params,'ll');
    
  }
  console.log(params,'p');
  if(!params.designerTags) params.designerTags = []
  if(!params.designerStyle) params.designerStyle = []
  
  
};

// 处理对话框保存数据
const handleDialogSaveData =(params: Record<string, any>)=>{
  if(params.vrFileUrls.length>0) {
    params.vrFileUrls=params.vrFileUrls.flatMap((item: any) =>
      item.fileUrlList.map((file: any) => ({
        'space':item.space,
        'fileUrl':file.url
      }))
    )
  }
  

};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  caseListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
// const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
//   params.province = value[0] || '';
//   params.city = value[1] || '';
//   params.area = value[2] || '';
// };
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
// 处理设置设计师信息
const handleSetDesignerInfo = (value: SelectValue, params: Record<string, any>) => {
  const userInfo = userStore.simpleUserList.find((item) => item.nickname === value) || {};
  params.designerPhone = dataEncryption.decrypt(userInfo.mobile);
  params.designerAvatar = userInfo.avatar;
  params.designerAvatarList = [];
  if (userInfo.avatar) params.designerAvatarList.push({ url: userInfo.avatar });
};
const handleClose = (index:any,tags:Record<string, any>[]) => {
  console.log(index);
  tags.splice(index, 1);
};

const handleClick = (event:any) => {
  console.log(event);
};
const inputVisible = ref(false)
const inputVisibleStyle = ref(false)
const handleInputEnter = (val:any,tags:Record<string, any>[]) => {
  if (val && !tags.some((item) => item === val)) {
    tags.push(val);
  }
  inputVisible.value = false;
};
const handleInputEnterStyle = (val:any,tags:Record<string, any>[]) => {
  if (val && !tags.some((item) => item === val)) {
    tags.push(val);
  }
  inputVisibleStyle.value = false;
};
const input = ref('');
const handleClickAdd = () => {
  inputVisible.value = true;
  nextTick(() => {
    input.value.focus();
  });
};
const inputStyle = ref('');
const handleClickAddStyle = () => {
  inputVisibleStyle.value = true;
  nextTick(() => {
    inputStyle.value.focus();
  });
};
</script>

<style lang="less" scoped>
.tag-block {
  margin-right: 10px;
}
</style>
